package com.xiaolin.oa.interceptor;

import com.xiaolin.oa.annotations.HasApi;
import com.xiaolin.oa.constants.ApiPermConstant;
import com.xiaolin.oa.model.dto.CurrentUser;
import com.xiaolin.oa.properties.ApiPermissionProperties;
import com.xiaolin.oa.utils.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author xiaolin
 * @description 用户授权拦截器
 * @since 2024/7/29
 */
@Slf4j
@Component
@EnableConfigurationProperties(ApiPermissionProperties.class)
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    private ApiPermissionProperties apiPermissionProperties;

    @Autowired
    private ContextUtil contextUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!apiPermissionProperties.isCheck()) {
            // 未开启接口权限，直接放行
            return true;
        }
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            HasApi hasApi = handlerMethod.getMethodAnnotation(HasApi.class);
            if (Objects.isNull(hasApi) || hasApi.value().length == 0) {
                // 接口未配置接口权限标识，禁止访问
                log.info("接口未配置接口权限标识，禁止访问，接口名：{}", handlerMethod.getMethod().getName());
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return false;
            }
            List<String> perms = Arrays.asList(hasApi.value());
            if (perms.contains(ApiPermConstant.COMMON_PERM)) {
                // 通用权限接口，只要登录就可访问
                return true;
            }
            CurrentUser currentUser = contextUtil.getCurrentUser();
            List<String> apiPermission = currentUser.getApiPermission();
            boolean hasApiPerm = false;
            for (String perm : perms) {
                if (apiPermission.contains(perm)) {
                    hasApiPerm = true;
                    break;
                }
            }
            if (!hasApiPerm) {
                // 用户未包含接口任何一个权限，不可访问
                log.info("用户未包含接口任何一个权限，不可访问，接口名：{}，用户包含权限：{}，接口需要权限：{}", handlerMethod.getMethod().getName(), apiPermission, perms);
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return false;
            }
        }
        return true;
    }
}
